from django.shortcuts import render

# Create your views here.
from rest_framework import status

from rest_framework.views import APIView
from rest_framework.response import Response

# from users.serializers import RegisterAPIViewSerializer
from celery_tasks.email.tasks import send_verify_mail
from users.serializers import RegisterAPIViewSerializer, UserInfoAPIViewSerializer, EmailSendAPIVIewSerializer, \
    AddAdressAPIViewSerializer, AddAddressSerializer
from users.utils import generate_save_token, generate_check_token
from .models import User, Address


# 判断用户是否存在
class RegisterUsernameCountAPIView(APIView):

    def get(self,request,username):

        count = User.objects.filter(username = username).count()

        context = {
            'count':count,
            'username':username
        }

        return Response(context)


# 验证手机号
# GET /users/phones/(?P<mobile>1[345789]\d{9})/count/
class RegisterMobileAPIView(APIView):

    def get(self,request,mobile):

        # 数据库中查找
        count = User.objects.filter(mobile=mobile).count()

        data = {

            'count':count,
            'mobile':mobile
        }
        return Response(data)


'''
注册后端实现 携带参数　post 请求  POST/users/
1 首先接收参数　手机号　用户名　短信验证吗　密码　密码２　统一协议
2　校验参数　选择使用的序列化器　因为user 继承的abs　所以重写它的方法　涉及到数据库　Ｇ 保存　给 user_id username
3 路由　　users/
4 返回username 和 user_id  还有　token
'''


class RegisterAPIView(APIView):

    def post(self,request):

        data = request.data

        serializer = RegisterAPIViewSerializer(data=data)
        serializer.is_valid(raise_exception=True)

        user = serializer.save()

        return Response({
            'token':user.token,
            'user_id':user.id,
            'username':user.username
                         })

'''
GET/users/infos/

１　必须返回的参数　手机号　用户名　id　email email_active


'''
from rest_framework.generics import RetrieveAPIView
from rest_framework.permissions import IsAuthenticated


class UserInfoAPIView(RetrieveAPIView):

    permission_classes = [IsAuthenticated]
    serializer_class = UserInfoAPIViewSerializer

    def get_object(self):

        return self.request.user


# '''
# 请求方式： GET/users/infos/
# ０　请求时携带的参数　email mobile username
# １　返回参数　id username mobile email email_active
# ２　校验参数　使用序列化器　Ｍ　
# ３　发送验证邮箱　
#
# '''
#
#
# class InfoAPIVIew(APIView):
#
#     def get(self,request):
#         data = request.query_params
#
#         serializer = UserInfoAPIViewSerializer(data=data)
#         serializer.is_valid(raise_exception=True)
#
#         return Response(serializer.data)

'''
１　点击保存　　要求前端传过来　email 的　参数　进行邮箱的发送 请求方式：PUT/users/emails/
２　使用django自带的发送系统进行发送
３　分为两个方向　由前端传两个参数　　邮箱和　user
４　我们将邮箱保存到数据库中　将是哪个用户的　将邮箱的标记位更改
５　我们进行邮箱验证的发送

'''


class EmailSendAPIVIew(APIView):

    def put(self,request):
        data = request.data
        user = request.user

        serializer = EmailSendAPIVIewSerializer(instance=user,data=data)
        serializer.is_valid(raise_exception=True)
        # 调用save()方法自动能够保存
        serializer.save()
        subject = '美多商场激活邮件'

        from_email = '美多商城<qi_rui_hua@163.com>'
        # recipient_list,   收件人列表
        email = data.get('email')
        message = ''

        recipient_list = [email]

        verify_url = generate_save_token(request.user.id, email)

        html_message = '<p>尊敬的用户您好！</p>' \
                       '<p>感谢您使用美多商城。</p>' \
                       '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                       '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)

        send_verify_mail.delay(subject=subject,
                  message=message,
                  from_email=from_email,
                  recipient_list=recipient_list,
                  html_message=html_message)
        return Response(serializer.data)



'''
激活邮箱的步骤
１　接收前端传过来的token
２　进行验证　进行解密　
３　取到加密的email id
４　根据id 进行更改数据库中的邮箱状态
５　返回响应　返回邮箱的更改状态

'''


class ActiveEmailAPIView(APIView):

    def get(self,request):
        data = request.query_params
        token = generate_check_token(data)

        if token is None:
            return Response({'msm':'过期'})

        id = token.get('id')
        email = token.get('email')
        try:
            user = User.objects.get(id=id,email=email)
        except User.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)

        user['email_active'] = True
        user.save()

        return Response({'msm':'OK'})


'''
要求前端发送过来　收件人　电话　邮箱　地址　用户的token
POST    /users/addresses/
请求方式

'''


# class AddAdressAPIView(APIView):
#     permission_classes = [IsAuthenticated]
#
#     def post(self,request):
#
#         data = request.data
#
#         serializer = AddAdressAPIViewSerializer(data=data,context={'request':request})
#         serializer.is_valid(raise_exception=True)
#
#         serializer.save()
#
#         return Response(serializer.data)



'''
新增地址的实现　
接收参数　收货人　所在地址　详细地址　手机号　邮箱和固定电话可以选填
'''
from rest_framework.permissions import IsAuthenticated


class AddAddressAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self,request):

        data = request.data

        serializer = AddAddressSerializer(data=data,context={'request':request})
        serializer.is_valid(raise_exception=True)

        serializer.save()

        return Response(serializer.data)

    def get(self,request):
        user = request.user
        try:
            add = Address.objects.filter(user_id = user.id)
        except Address.DoesNotExist:
            return Response(status=status.HTTP_204_NO_CONTENT)
        serializer = AddAddressSerializer(instance=add,many=True)
        # serializer.is_valid(raise_exception=True)

        return Response(serializer.data)